package userserv

import (
	"codedef"
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"strconv"
	"task"
)

type lTask struct {
	Name        string `json:"name"`
	Id          string `json:"id"`
	Type        string `json:"type"`
	PerBatch    int    `json:"perbatch"`
	Duration    int    `json:"duration"`
	Status      string `json:"status"`
	Description string `json:"description"`
	Farm        string `json:"farm"`
}

func onLoadTasks(w http.ResponseWriter, r *http.Request) {
	var account string
	account = r.Header.Get("account")
	log.Printf("loadTasks, account:%s\n", account)

	taskId := r.URL.Query().Get("tid")
	//farmId := r.URL.Query().Get("fid")

	conn := rhelper.Pool().Get()
	defer conn.Close()

	vv, err := redis.Strings(conn.Do("HMGET", rhelper.TaskHash+taskId, "type", "perbatch", "duration", "name", "farm", "description"))
	if err != nil {
		log.Println("load task info failed:", err)
		replyError(w, codedef.ERR_TASK_NOT_EXIST)
		return
	}

	lt := &lTask{}
	lt.Type = vv[0]
	lt.PerBatch, _ = strconv.Atoi(vv[1])
	lt.Duration, _ = strconv.Atoi(vv[2])
	lt.Id = taskId
	lt.Name = vv[3]

	if task.Mgr.IsTaskRunning(taskId) {
		lt.Status = "run"
	} else {
		lt.Status = "stop"
	}

	farmName, _ := redis.String(conn.Do("HGET", rhelper.FarmHash+vv[4], "name"))
	lt.Farm = farmName

	lt.Description = vv[5]

	buf, err := json.Marshal(lt)
	if err != nil {
		log.Println("onLoadTask failed:", err)
		replyError(w, codedef.ERR_ENCODE)
		return
	}

	w.Write(buf)
}

func init() {
	myMux.muxHandlers.HandleFunc("/loadTask", onLoadTasks)
}
